﻿using System;
using System.Web;
using NSuggest.Jsonp.Core;

namespace GMCB.Jsonp.Example
{
    /// <summary>
    /// An example of how to use JsonpEngine inside a IHttpHandler.
    /// </summary>
    public class HelloJsonpService : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var myQuery = new MyQuery();
            // Instantiate the JsonpEngine<Hello>, providing a function that delivers Hello objects given a HttpContext object.
            var engine = new JsonpEngine(myQuery.PerformQuery)
                             {CallbackParameter = "cb"};

            // Set a custom callback parameter name. 
            // Calls to the service: http://example.com/helloworld.json?cb=foo.
            // Return JSONP: [text/javascript] foo({"Message":"Hello world!"})

            // (Optional) subscribe to events
            engine.ErrorEvent += ((obj, e) => Console.WriteLine("An error occured. The HTTP status code was: " + e.HttpStatusCode) );
            engine.SuccessEvent += ((obj, e) => Console.WriteLine("Great success occured, the message was: " + e.Result.Message));
            engine.CompletedEvent += ((obj, e) => Console.WriteLine("It's all over"));

            // Handle context
            engine.Execute(context);

        }

        public bool IsReusable
        {
            get { return false; }
        }
    }

    public class MyQuery
    {
        public Hello PerformQuery(HttpContext context)
        {
            return new Hello() {Message = "Hello JSONP"};
        }
    }
}